﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Sherwood.Security;
using Sherwood.SignOn.Server.Models.Configuration;

namespace Sherwood.SignOn.Server.Models.Repositories.Config
{
    /// <summary>
    /// Implementation of the IClientRepository interface which reads clients from web/app.config.
    /// </summary>
    public class ConfigClientRepository : IClientRepository
    {
        Dictionary<string, ClientsElement> _clients = null;

        public ConfigClientRepository()
        {
            LoadClients();
        }

        protected void LoadClients()
        {
            lock (this)
            {
                _clients = new Dictionary<string, ClientsElement>();
                foreach (ClientsElement client in SignOnServerSection.Instance.Clients)
                {
                    _clients[client.Code] = client;
                }
            }
        }

        protected Dictionary<string, ClientsElement> Clients
        {
            get
            {
                if (_clients == null)
                {
                    LoadClients();
                }
                return _clients;
            }
        }


        public bool VerifyMessage(string clientCode, string messageText, string messageSignature)
        {
            if (!string.IsNullOrEmpty(clientCode))
            {
                ClientsElement client = Clients.ContainsKey(clientCode) ? Clients[clientCode] : null;
                if (client != null && !string.IsNullOrEmpty(client.RsaPublicKey))
                {
                    Rsa rsa = null;
                    try
                    {
                        rsa = Rsa.FromPublicKey(client.RsaPublicKey);
                    }
                    catch //problem with key
                    {
                        rsa = null;
                    }
                    if (rsa == null)
                    {
                        return false;
                    }
                    bool verified = false;
                    try
                    {
                        verified = rsa.SHA1Verify(messageText, messageSignature);
                    }
                    catch
                    {
                        verified = false;
                    }
                    return verified;
                }
            }
            return false;
        }

        public string GetRsaPublicKey(string clientCode)
        {
            if (Clients.ContainsKey(clientCode))
            {
                return Clients[clientCode].RsaPublicKey;
            }
            return null;
        }
    }
}